#define _CRT_SECURE_NO_WARNINGS 1
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define endl '\n'
const int N = 1e6 + 10;
list<int> dq[N];

int main() {
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	int q; cin >> q;
	while (q--) {
		string s; cin >> s;
		if (s == "push_back") {
			int a, x; cin >> a >> x;
			dq[a].push_back(x);
		}
		if (s == "pop_back") {
			int a; cin >> a;
			if(!dq[a].empty()) dq[a].pop_back();
		}
		if (s == "push_front") {
			int a, x; cin >> a >> x;
			dq[a].push_front(x);
		}
		if (s == "pop_front") {
			int a; cin >> a;
			if(!dq[a].empty()) dq[a].pop_front();
		}
		if (s == "size") {
			int a; cin >> a;
			cout << dq[a].size() << endl;
		}
		if (s == "front") {
			int a; cin >> a;
			if (!dq[a].empty()) cout << dq[a].front() << endl;
		}
		if (s == "back") {
			int a; cin >> a;
			if (!dq[a].empty()) cout << dq[a].back() << endl;
		}
	}
	return 0;
}